from flask import Flask, g, request
from flask_babel import Babel, _
from config.default import Config
import logging

babel = Babel()

def get_locale():
    # 从 URL 路径获取语言代码
    try:
        lang_code = request.path.split('/')[1]
        if lang_code in Config.LANGUAGES:
            return lang_code.replace('-', '_')
    except:
        pass
    return Config.BABEL_DEFAULT_LOCALE

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    # 配置日志
    if app.debug:
        app.logger.setLevel(logging.DEBUG)
        
    # 初始化 Babel
    babel.init_app(app, locale_selector=get_locale)

    # 注册蓝图
    from app.routes import main_bp
    app.register_blueprint(main_bp)

    # 添加上下文处理器
    @app.context_processor
    def utility_processor():
        return {
            'g': g,
            '_': _  # 添加翻译函数到模板上下文
        }

    return app 